<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="部门id" prop="deptId">
                            <el-input
                                    v-model="queryParams.deptId"
                                    placeholder="请输入部门id"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item> -->
      <el-form-item label="岗位名称" prop="post">
        <el-input v-model="queryParams.post" placeholder="请输入岗位名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="修改时间" prop="modifyTime">
                            <el-date-picker clearable
                                            v-model="queryParams.modifyTime"
                                            type="date"
                                            value-format="YYYY-MM-DD"
                                            placeholder="请选择修改时间">
                            </el-date-picker>
                        </el-form-item> -->
      <!-- <el-form-item label="岗位类型" prop="demandType">
        <el-select v-model="queryParams.demandType" placeholder="按类型查询" clearable style="width:200px;">
          <el-option v-for="dict in bus_require_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="审核状态" prop="approveState">
        <el-select v-model="queryParams.approveState" placeholder="选择审核状态" clearable style="width:200px;">
          <el-option v-for="dict in bus_requireapprove_state" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="过需求期时间" prop="expirationTime">
                            <el-date-picker clearable
                                            v-model="queryParams.expirationTime"
                                            type="date"
                                            value-format="YYYY-MM-DD"
                                            placeholder="请选择过需求期时间">
                            </el-date-picker>
                        </el-form-item> -->
      <el-form-item label="生效状态" prop="requireState">
        <el-select v-model="queryParams.requireState" placeholder="选择需求状态" clearable style="width:200px;">
          <el-option v-for="dict in bus_require_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="单位名称" prop="unit">
        <el-input v-model="queryParams.unit" placeholder="请输入单位名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="编制课题" prop="project">
        <el-input v-model="queryParams.project" placeholder="请输入规划编制、重点课题名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="意向招收" prop="intention">
        <el-input v-model="queryParams.intention" placeholder="请输入意向高校或专业" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input v-model="queryParams.contact" placeholder="请输入联系人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="联系方式" prop="number">
                            <el-input
                                    v-model="queryParams.number"
                                    placeholder="请输入联系方式"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item> -->
      <!-- <el-form-item label="删除时间" prop="delTime">
                            <el-date-picker clearable
                                            v-model="queryParams.delTime"
                                            type="date"
                                            value-format="YYYY-MM-DD"
                                            placeholder="请选择删除时间">
                            </el-date-picker>
                        </el-form-item> -->
      <el-form-item label="地市信息" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择地市" clearable filterable style="width: 180px;">
          <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['bus:require:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['bus:require:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple || batchDeleteDisabled" @click="handleDelete"
          v-hasPermi="['bus:require:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['bus:require:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="requireList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="需求ID" align="center" prop="requireId" /> -->
      <!-- <el-table-column label="部门id" align="center" prop="deptId" /> -->


      <!-- <el-table-column label="修改时间" align="center" prop="modifyTime" width="180">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.modifyTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column> -->
      <!-- <el-table-column label="岗位类型" align="center" prop="demandType" width="130px">
        <template #default="scope">
          <dict-tag :options="bus_require_type" :value="scope.row.demandType" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="需求过期时间" align="center" prop="expirationTime" width="180">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.expirationTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column> -->

      <el-table-column label="地市信息" align="center" prop="parentDeptName" width="130px">
        <template #default="scope">
          <span v-if="scope.row.deptId === 100">全部地市</span>
          <span v-else>{{ scope.row.parentDeptName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位名称" align="center" prop="unit" width="130px" />
      <el-table-column label="规划编制、重点课题" align="center" prop="project" width="180px" />
      <el-table-column label="岗位名称" align="center" prop="post" width="130px" />
      <!-- <el-table-column label="意向高校或专业" align="center" prop="intention" width="150px"/> -->
      <el-table-column label="岗位情况" align="center" width="130px">
        <template #default="{ row }">
          <span v-if="row.recruited >= row.quantity" class="dict-tag el-tag el-tag--warning">招满</span>
          <span v-else>{{ row.recruited }}/{{ row.quantity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="approveState" width="130px">
        <template #default="{ row }">
          <span v-if="row.approveState == 1" class="dict-tag el-tag el-tag--warning">待审核</span>
          <span v-else-if="row.approveState == 2" class="dict-tag el-tag el-tag--warning">被驳回</span>
          <span v-else class="dict-tag el-tag el-tag--success">已通过</span>
        </template>
      </el-table-column>
      <!--  <el-table-column label="联系人" align="center" prop="contact" />
                    <el-table-column label="联系方式" align="center" prop="number" />
                    <el-table-column label="备注" align="center" prop="remark" /> -->
      <!-- <el-table-column label="删除时间" align="center" prop="delTime" width="180">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.delTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-space>
            <el-button link type="primary" @click="showContentDetail(scope.row)">查看详情</el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['bus:require:edit']">修改</el-button>
            <el-button
              v-if="scope.row.approveState != 1"
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['bus:require:remove']"
            >
              删除
            </el-button>
            <el-button link type="primary" @click="goToApplyList(scope.row)" v-hasPermi="['signup:approve:list']">
              查看报名列表
            </el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改岗位需求发布对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="requireRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="岗位名称" prop="post">
          <el-input v-model="form.post" placeholder="请输入岗位名称" maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item label="课题研究目标" prop="content">
          <editor
            v-model="form.content"
            :min-height="192"
            maxlength="20000"
          />
        </el-form-item>
        <!-- <el-form-item label="岗位类型" prop="demandType">
          <el-select v-model="form.demandType" placeholder="选择类型" style="width:220px">
            <el-option v-for="dict in bus_require_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="过期时间" prop="expirationTime">
          <el-date-picker
            clearable
            v-model="form.expirationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择过期时间"
            :disabled-date="disabledPastDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="岗位数量" prop="quantity" style="width: 100%; display: flex; align-items: center;">
          <el-input-number v-model="form.quantity" :min="1" :max="9999" :step="1" placeholder="请输入岗位数量"
            style="width: 180px; margin-right: 24px;" />
          <!-- 只在修改时显示已招收 -->
          <span v-if="form.requireId" style="white-space: nowrap; display: flex; align-items: center;">
            <span style="margin-right: 4px;">已招收：</span>
            <el-input v-model="form.recruited" readonly size="default"
              style="width: 80px; background: transparent; border: none; padding: 0; color: #606266;"
              :input-style="{ textAlign: 'left', background: 'transparent', border: 'none', boxShadow: 'none' }" />
          </span>
        </el-form-item>
        <el-form-item label="单位名称" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位名称" maxlength="30"
            show-word-limit/>
        </el-form-item>
        <el-form-item label="编制课题" prop="project">
          <el-input v-model="form.project" placeholder="请输入规划编制、重点课题名称" maxlength="200"
            show-word-limit/>
        </el-form-item>
        <el-form-item label="意向招收" prop="intention">
          <el-input v-model="form.intention" placeholder="请输入意向高校或专业，没有请填无" maxlength="100"
            show-word-limit/>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人" maxlength="10"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="number">
          <el-input v-model="form.number" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容，没有请填无"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <!-- <el-form-item label="创建人名称" prop="createName">
                                    <el-input v-model="form.createName" placeholder="请输入创建人名称" />
                                </el-form-item> -->
        <!-- <el-form-item label="删除时间" prop="delTime">
                                    <el-date-picker clearable
                                                    v-model="form.delTime"
                                                    type="date"
                                                    value-format="YYYY-MM-DD"
                                                    placeholder="请选择删除时间">
                                    </el-date-picker>
                                </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="岗位详情" v-model="showContentDialog" width="800px" :style="{ maxWidth: '90vw' }" append-to-body>
      <div v-html="contentDetail" style="word-break: break-all; max-height: 500px; overflow: auto; padding-right: 8px;">
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showContentDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Require">
  import {
    listRequire,
    getRequire,
    delRequire,
    addRequire,
    updateRequire
  } from "@/api/bus/require";
  import { listDept } from '@/api/system/dept';
  import { ref, onMounted } from 'vue';

  const {
    proxy
  } = getCurrentInstance();
  const {
    bus_requireapprove_state,
    bus_require_state,
    bus_require_type
  } = proxy.useDict('bus_requireapprove_state', 'bus_require_state', 'bus_require_type');

  const requireList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const batchDeleteDisabled = ref(false);

  const showContentDialog = ref(false);
  const contentDetail = ref("");

  const deptOptions = ref([]);
  onMounted(() => {
    listDept().then(res => {
      deptOptions.value = (res.data || []).filter(item => Number(item.parentId) === 100 && item.status === '0' && item.delFlag === '0');
    });
  });

  function showContentDetail(row) {
    // 课题研究目标内容
    let content = row.content || '';
    // 岗位数量和已招收
    let quantity = row.quantity !== undefined && row.quantity !== null ? row.quantity : '';
    let recruited = row.recruited !== undefined && row.recruited !== null ? row.recruited : '';
    // 意向高校或专业
    let intention = row.intention ? row.intention : '';
    // 联系人、联系方式、备注
    let contact = row.contact ? row.contact : '';
    let number = row.number ? row.number : '';
    let remark = row.remark ? row.remark : '';
    // 过期时间
    let expirationTime = row.expirationTime ?
      proxy.parseTime ?
      proxy.parseTime(row.expirationTime, '{y}-{m}-{d}') :
      row.expirationTime :
      '';
    // 最新审核意见
    let latestApproveReview = row.latestApproveReview ? row.latestApproveReview : '';
    // 拼接内容
   
    let unit = row.unit ? row.unit : '';
    let project = row.project ? row.project : '';
    let post = row.post ? row.post : '';
    contentDetail.value = `
<div>
      <div class="content-detail-img-box" style="margin-bottom: 16px; border: 1px solid #000; border-radius: 4px; padding: 12px 16px; background: #fff;">
        <div style="margin-bottom: 8px;"><strong>单位名称：</strong>${unit}</div>
        <div style="margin-bottom: 8px;"><strong>规划编制、重点课题：</strong>${project}</div>
        <div style="margin-bottom: 8px;"><strong>岗位名称：</strong>${post}</div>
    </div>
    <div class="content-detail-img-box" style="margin-bottom: 16px; border: 1px solid #000; border-radius: 4px; padding: 12px 16px; background: #fff;">
        <strong>课题研究目标：</strong><br>
        <div class="ql-editor">${content}</div>
    </div>
    <div style="margin-bottom: 8px;"><strong>意向高校或专业：</strong>${intention}</div>
    <div style="margin-bottom: 8px;"><strong>岗位数量：</strong>${quantity}</div>
    <div style="margin-bottom: 8px;"><strong>已招收：</strong>${recruited}</div>
    <div style="margin-bottom: 8px;"><strong>联系人：</strong>${contact}</div>
    <div style="margin-bottom: 8px;"><strong>联系方式：</strong>${number}</div>
    <div style="margin-bottom: 8px;"><strong>备注：</strong>${remark}</div>
    <div style="margin-bottom: 8px;"><strong>过期时间：</strong>${expirationTime}</div>
    <div style="margin-bottom: 8px;"><strong>最新审核意见：</strong>${latestApproveReview}</div>
</div>
<style>
    .content-detail-img-box img { max-width: 100%; height: auto; display: block; margin: 0 auto; }
</style>
<!-- 引入 Quill 编辑器样式，仅在本页生效 -->
<style src="@vueup/vue-quill/dist/vue-quill.snow.css"></style>
`;
    showContentDialog.value = true;
  }

  const router = useRouter();
  
  function goToApplyList(row) {
    router.push({
      path: '/signup/approve/index/' + row.requireId,
      // query: { requireId: row.requireId }
    });
  }

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      deptId: null,
      post: null,
      content: null,
      modifyTime: null,
      demandType: null,
      approveState: null,
      expirationTime: null,
      requireState: null,
      unit: null,
      project: null,
      intention: null,
      contact: null,
      number: null,
      delTime: null,
      recruited: null
    },
    rules: {
      post: [
        { required: true, message: '请输入岗位名称', trigger: 'blur' }
      ],
      /*demandType: [
        { required: true, message: '请选择岗位类型', trigger: 'change' }
      ],*/
      quantity: [
        { required: true, message: '请输入岗位数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '岗位数量不能小于1', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            // 这里的this不可用，需用data.form
            if (value < data.form.recruited) {
              callback(new Error('岗位数量不能小于已招收人数'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ],
      unit: [
        { required: true, message: '请输入单位名称', trigger: 'blur' }
      ],
      project: [
        { required: true, message: '请输入规划编制、重点课题名称', trigger: 'blur' }
      ],
      intention: [
        { required: true, message: '请输入意向高校或专业', trigger: 'blur' }
      ],
      contact: [
        { required: true, message: '请输入联系人', trigger: 'blur' }
      ],
      number: [
        { required: true, message: '请输入联系方式', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入课题研究目标', trigger: 'blur' }
      ],
      expirationTime: [
        { required: true, message: '请选择过期时间', trigger: 'change' }
      ],
      remark: [
        { required: true, message: '请输入备注，没有请填无', trigger: 'blur' }
      ]
    }
  });

  const {
    queryParams,
    form,
    rules
  } = toRefs(data);

  const quantityOptions = [{
    label: '招满',
    value: 0
  }];

  // 只能选择今天及以后的日期
  function disabledPastDate(time) {
    return time.getTime() < new Date(new Date().setHours(0,0,0,0)).getTime();
  }

  /** 查询岗位需求发布列表 */
  function getList() {
    loading.value = true;
    listRequire(queryParams.value).then(response => {
      requireList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
      requireId: null,
      deptId: null,
      post: null,
      content: null,
      createTime: null,
      modifyTime: null,
      demandType: null,
      approveState: null,
      expirationTime: null,
      requireState: null,
      creatorId: null,
      quantity: null,
      unit: null,
      project: null,
      intention: null,
      contact: null,
      number: null,
      remark: null,
      createName: null,
      delTime: null,
      recruited: null,
      latestApproveReview: null
    };
    proxy.resetForm("requireRef");
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.requireId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
    // 新增逻辑：只要有一条待审核，就禁用批量删除
    batchDeleteDisabled.value = selection.some(item => item.approveState == 1); // 1为待审核
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加岗位需求发布";
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    const _requireId = row.requireId || ids.value
    getRequire(_requireId).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改岗位需求发布";
    });
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["requireRef"].validate(valid => {
      if (valid) {
        if (form.value.requireId != null) {
          updateRequire(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addRequire(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    let message = '';
    let _requireIds;
    if (row && row.requireId) {
      // 单个删除
      _requireIds = row.requireId;
      message = `是否确认删除岗位“${row.post || ''}”？`;
    } else {
      // 批量删除
      _requireIds = ids.value;
      message = `是否确认删除选中的${_requireIds.length}条岗位需求？`;
    }
    proxy.$modal.confirm(message).then(function() {
      return delRequire(_requireIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('bus/require/export', {
      ...queryParams.value
    }, `require_${new Date().getTime()}.xlsx`)
  }

  getList();
</script>